<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepSeek文本生成器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .container {
            width: 90%;
            max-width: 900px;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
            padding: 30px;
        }
        
        header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 1px solid #eee;
        }
        
        h1 {
            color: #2c3e50;
            font-size: 2.5rem;
            margin-bottom: 10px;
            background: linear-gradient(90deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }
        
        .api-config {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            border-left: 4px solid #667eea;
        }
        
        .api-config h3 {
            margin-bottom: 15px;
            color: #2c3e50;
        }
        
        .input-group {
            margin-bottom: 25px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2c3e50;
        }
        
        input, textarea, select {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        input:focus, textarea:focus, select:focus {
            border-color: #667eea;
            outline: none;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        textarea {
            min-height: 120px;
            resize: vertical;
        }
        
        .form-row {
            display: flex;
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .form-row .input-group {
            flex: 1;
            margin-bottom: 0;
        }
        
        button {
            background: linear-gradient(90deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
            margin-top: 10px;
        }
        
        button:hover:not(:disabled) {
            transform: translateY(-3px);
            box-shadow: 0 7px 15px rgba(102, 126, 234, 0.4);
        }
        
        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        
        .preview-section {
            margin-top: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
            display: none;
        }
        
        .preview-content {
            max-height: 300px;
            overflow-y: auto;
            padding: 15px;
            background: white;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
            white-space: pre-wrap;
            line-height: 1.6;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 25px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            transform: translateX(150%);
            transition: transform 0.4s;
            z-index: 1000;
        }
        
        .notification.success {
            background: #2ecc71;
            color: white;
        }
        
        .notification.error {
            background: #e74c3c;
            color: white;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .loading {
            display: none;
            text-align: center;
            margin: 20px 0;
        }
        
        .spinner {
            border: 5px solid #f3f3f3;
            border-top: 5px solid #667eea;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .token-info {
            display: flex;
            justify-content: space-between;
            margin-top: 5px;
            font-size: 0.9rem;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>DeepSeek文本生成器</h1>
            <p class="subtitle">使用DeepSeek API生成高质量的文本内容</p>
        </header>
        
        <main>
            <div class="api-config">
                <h3>API配置</h3>
                <div class="input-group">
                    <label for="apiKey">DeepSeek API密钥</label>
                    <input type="password" id="apiKey" placeholder="请输入您的DeepSeek API密钥">
                    <div class="token-info">
                        <span>获取API密钥：<a href="https://platform.deepseek.com/api_keys" target="_blank">DeepSeek平台</a></span>
                    </div>
                </div>
            </div>
            
            <div class="input-group">
                <label for="prompt">文本提示词</label>
                <textarea id="prompt" placeholder="请详细描述您想要生成的文本内容...">请写一篇关于人工智能在教育领域应用的文章，包括个性化学习、智能辅导和教学评估等方面的内容。</textarea>
            </div>
            
            <div class="form-row">
                <div class="input-group">
                    <label for="wordCount">文本长度</label>
                    <select id="wordCount">
                        <option value="300">短文本 (300字)</option>
                        <option value="500" selected>中等文本 (500字)</option>
                        <option value="800">长文本 (800字)</option>
                        <option value="1000">超长文本 (1000字)</option>
                    </select>
                </div>
                
                <div class="input-group">
                    <label for="fileName">文件名称</label>
                    <input type="text" id="fileName" placeholder="输入文件名（不含扩展名）" value="AI教育应用文章">
                </div>
            </div>
            
            <div class="input-group">
                <label for="writingStyle">写作风格</label>
                <select id="writingStyle">
                    <option value="academic">学术风格</option>
                    <option value="professional" selected>专业风格</option>
                    <option value="casual">随意风格</option>
                    <option value="creative">创意风格</option>
                </select>
            </div>
            
            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>正在调用DeepSeek API生成文本，请稍候...</p>
                <div class="token-info" id="tokenUsage">预计耗时：15-30秒</div>
            </div>
            
            <button id="generateBtn">调用DeepSeek生成文本</button>
            
            <div class="preview-section" id="previewSection">
                <h3>生成的文本内容</h3>
                <div class="preview-content" id="previewContent"></div>
                
                <div class="token-info" id="actualTokenUsage"></div>
                
                <button id="saveBtn">下载文本文件</button>
            </div>
        </main>
    </div>
    
    <div class="notification" id="notification">操作成功！</div>

    <script>
        class DeepSeekTextGenerator {
            constructor() {
                this.apiKey = '';
                this.baseURL = 'https://api.deepseek.com/v1';
                this.generateBtn = document.getElementById('generateBtn');
                this.saveBtn = document.getElementById('saveBtn');
                this.previewSection = document.getElementById('previewSection');
                this.previewContent = document.getElementById('previewContent');
                this.loading = document.getElementById('loading');
                this.notification = document.getElementById('notification');
                this.actualTokenUsage = document.getElementById('actualTokenUsage');
                
                this.initEventListeners();
            }
            
            initEventListeners() {
                this.generateBtn.addEventListener('click', () => this.generateText());
                this.saveBtn.addEventListener('click', () => this.saveFile());
                
                // 监听API密钥输入
                document.getElementById('apiKey').addEventListener('input', (e) => {
                    this.apiKey = e.target.value.trim();
                    this.updateGenerateButton();
                });
            }
            
            updateGenerateButton() {
                this.generateBtn.disabled = !this.apiKey;
                this.generateBtn.textContent = this.apiKey ? 
                    '调用DeepSeek生成文本' : 
                    '请先输入API密钥';
            }
            
            async generateText() {
                const prompt = document.getElementById('prompt').value;
                const wordCount = document.getElementById('wordCount').value;
                const writingStyle = document.getElementById('writingStyle').value;
                
                if (!this.validateInputs(prompt)) return;
                
                this.showLoading(true);
                
                try {
                    const generatedText = await this.callDeepSeekAPI(prompt, wordCount, writingStyle);
                    this.displayGeneratedText(generatedText);
                    this.showNotification('文本生成成功！', 'success');
                } catch (error) {
                    console.error('API调用失败:', error);
                    this.showNotification(`生成失败: ${error.message}`, 'error');
                } finally {
                    this.showLoading(false);
                }
            }
            
            validateInputs(prompt) {
                if (!this.apiKey) {
                    this.showNotification('请输入DeepSeek API密钥', 'error');
                    return false;
                }
                
                if (!prompt.trim()) {
                    this.showNotification('请输入文本提示词', 'error');
                    return false;
                }
                
                return true;
            }
            
            async callDeepSeekAPI(prompt, wordCount, writingStyle) {
                const styleMap = {
                    'academic': '学术论文风格，严谨客观',
                    'professional': '专业报告风格，逻辑清晰',
                    'casual': '轻松随意的博客风格',
                    'creative': '富有创意的文学风格'
                };
                
                const systemPrompt = `你是一个专业的写作助手。请根据用户的要求生成指定字数的文本。
要求：
1. 写作风格：${styleMap[writingStyle]}
2. 目标字数：${wordCount}字左右
3. 内容要连贯、有逻辑性
4. 直接输出正文内容，不需要额外的说明`;

                const requestBody = {
                    model: "deepseek-chat",
                    messages: [
                        {
                            role: "system",
                            content: systemPrompt
                        },
                        {
                            role: "user",
                            content: prompt
                        }
                    ],
                    max_tokens: Math.min(parseInt(wordCount) * 2, 4000),
                    temperature: 0.7,
                    stream: false
                };
                
                const response = await fetch(`${this.baseURL}/chat/completions`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.apiKey}`
                    },
                    body: JSON.stringify(requestBody)
                });
                
                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.error?.message || `HTTP ${response.status}`);
                }
                
                const data = await response.json();
                
                // 显示token使用情况
                if (data.usage) {
                    this.actualTokenUsage.innerHTML = `
                        Token使用: 输入${data.usage.prompt_tokens} / 输出${data.usage.completion_tokens} / 总计${data.usage.total_tokens}
                    `;
                }
                
                return data.choices[0].message.content;
            }
            
            displayGeneratedText(text) {
                this.previewContent.textContent = text;
                this.previewSection.style.display = 'block';
                this.previewSection.scrollIntoView({ behavior: 'smooth' });
            }
            
            saveFile() {
                const fileName = document.getElementById('fileName').value;
                const content = this.previewContent.textContent;
                
                if (!fileName.trim()) {
                    this.showNotification('请输入文件名', 'error');
                    return;
                }
                
                if (!content) {
                    this.showNotification('没有可保存的内容', 'error');
                    return;
                }
                
                const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `${fileName}.txt`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                this.showNotification(`文件 ${fileName}.txt 下载成功！`, 'success');
            }
            
            showLoading(show) {
                this.loading.style.display = show ? 'block' : 'none';
                this.generateBtn.disabled = show;
                this.generateBtn.textContent = show ? '生成中...' : '调用DeepSeek生成文本';
            }
            
            showNotification(message, type = 'success') {
                this.notification.textContent = message;
                this.notification.className = `notification ${type} show`;
                
                setTimeout(() => {
                    this.notification.classList.remove('show');
                }, 4000);
            }
        }
        
        // 初始化应用
        document.addEventListener('DOMContentLoaded', () => {
            new DeepSeekTextGenerator();
        });
    </script>
</body>
</html>